<?php
date_default_timezone_set('PRC');

/**
 * 请求HTML页面
 */
function http($url, $post_data = [], $cookie = '')
{
	//初始化
	$ch = curl_init();
	
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	// curl_setopt($ch, CURLOPT_HEADER, 0);

	// $proxy = '127.0.0.1';
	// curl_setopt($ch, CURLOPT_PROXY, $proxy);
	// $proxyport = '8888';
	// curl_setopt($ch, CURLOPT_PROXYPORT, $proxyport);

	// post数据
	if (count($post_data)) {
		$post_str = http_build_query($post_data);
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post_str);
	}

	// cookie
	if (empty($cookie)) {
		$cookie_file = __DIR__.'/cookie.txt';
		curl_setopt($ch, CURLOPT_COOKIEJAR,  $cookie_file);
		curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);

	} else {
		curl_setopt($ch, CURLOPT_COOKIE, $cookie);
	}

	// UA
	$ua = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) '
		. 'AppleWebKit/537.36 (KHTML, like Gecko) '
		. 'Chrome/62.0.3202.62 Safari/537.36';
	curl_setopt($ch, CURLOPT_USERAGENT, $ua); 

	//执行并获取HTML文档内容
	$output = curl_exec($ch);

	$info = curl_getinfo($ch);

	curl_close($ch);
	return $output;
}


/**
 * 下载图片
 */
function down($url, $path = 'images/')
{
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
	$cookie_file = __DIR__.'/cookie.txt';
	curl_setopt($ch, CURLOPT_COOKIEJAR,  $cookie_file);
	curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
	$file = curl_exec($ch);
	if (false == $file) {
		return false;
	}
	curl_close($ch);
	return $file;
}


/**
 * 对识别的内容做修正
 */
function code_replace($code_str)
{
	// 字母<6个直接return false; 接着请求新的验证码
	$len = strlen($code_str);
	if ($len < 6) {
		return false;
	}

	// 替换 0 1 2
	$search  = ['0', '1', '2', '|'];
	$replace = ['O', 'i', 'Z', 'i'];
	$code_str = str_replace($search, $replace, $code_str);

	// 去掉非a-z,0-9的字符
	// 65～90为26个大写英文字母，97～122号为26个小写英文字母 48~57
	$new = '';
	for ($i=0; $i < $len; $i++) { 
		$num = ord($code_str[$i]);
		if (($num>64 && $num<91) 
			|| ($num>96 && $num<122) 
			|| ($num>47 && $num<58)) {
			$new .= strtoupper($code_str[$i]);
		}
	}
	$code_str = $new;

	return $code_str;
}


/**
 * 匹配网页信息
 */
function get_info($html)
{
	if (strlen($html) < 100) {
		return [];
	}
	$pattern = '/<td align="center" class="bxy">(.*?)<\/td>/i';
	$ret = preg_match_all($pattern, $html, $matches);
	if ($ret < 1) {
		return [
			'unit'=>'',
			'type'=>'',
			'no'=>'',
			'title'=>'',
			'index'=>'',
			'date'=>'',
			'limit'=>''
		];
	}

	$data = [];
	foreach ($matches[1] as $key => &$val) {
		$val = trim(strip_tags(str_replace('&nbsp;','', $val)));
		switch ($key) {
			case 0: // 主办单位名称
				$data['unit'] = $val;
				break;
			case 1: // 主办性质
				$data['type'] = $val;
				break;
			case 2: // 网站备案/许可证号
				$data['no'] = $val;
				break;
			case 3: // 网站名称
				$data['title'] = $val;
				break;
			case 4: // 网站首页网址
				$data['index'] = $val;
				break;
			case 5: // 审核时间
				$val = date('Y-m-d', strtotime($val));
				$data['date'] = $val;
				break;
			case 6: // 是否限制接入
				$data['limit'] = $val;
				break;
			default:
				# code...
				break;
		}
	}
	return $data;
}

/**
 * 输入要查询的数据
 */
function input_data()
{
	// 读入文件
	$file = dirname(__DIR__).'/conf/input.txt';
	if (!file_exists($file)) {
		exit('输入文件不存在!!!');
	}
	$text = file_get_contents($file);
	$data = explode(PHP_EOL, $text);

	// 处理成域名
	foreach ($data as &$item) {
		$item = explode(',', trim($item, ','));
	}

	return $data;
}

/**
 * 输出CVS文件格式
 */
function output_data($data)
{
	$file = dirname(__DIR__).'/conf/output.csv';
	if (!file_exists($file)) {
		$title = '网站名称,域名,ICP号,主办单位名称,主办性质,网站备案/许可证号,网站名称,网站首页网址,审核时间,是否限制接入';
		file_put_contents($file, $title);
	}
	$str = PHP_EOL . "{$data['link']},{$data['unit']},{$data['type']},{$data['no']},"
		. "{$data['title']},{$data['index']},{$data['date']},{$data['limit']}";
	file_put_contents($file, $str, FILE_APPEND);
}


/**
 * 转换秒为 时:分:秒
 */
function sec2time($sec)
{
    $result = '00:00:00';  
    if ($sec>0) {  
        $hour   = floor($sec/3600);  
        $minute = floor(($sec-3600 * $hour)/60);  
        $second = floor((($sec-3600 * $hour) - 60 * $minute) % 60);  
        $result = sprintf('%02d:%02d:%02d', $hour, $minute, $second);
    }  
    return $result;  
}